package com.xhwl.centiotdata.suppliersystem.dahuaIcc;

import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.constant.DaHuaIccConstant;
import com.xhwl.centiotdata.pojo.dto.dahua.*;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.service.IOrgInfoService;
import com.xhwl.centiotdata.service.cent.IAuthAccountCentService;
import com.xhwl.centiotdata.suppliersystem.dahua.GeneralDaHuaHandler;
import com.xhwl.centiotdata.utils.UploadUtils;
import com.xhwl.common.dto.auth.PedestrianAuthDTO;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.dto.cent.pedes.OpenDoorRecordDTO;
import com.xhwl.common.enums.CodeEnum;
import com.xhwl.common.enums.pedestrian.DoorActionEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.auth.AuthAccountMapping;
import com.xhwl.common.pojo.cent.iot.OrgInfo;
import com.xhwl.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * @Author： wangyiling
 * @Description：
 * @Date 2022/08/11/ 09:44
 */
@Service
public class PedestrianDaHuaIccHandler {
    @Autowired
    private IAuthAccountCentService authAccountCentService;
    private static final Logger log = LoggerFactory.getLogger(PedestrianDaHuaIccHandler.class);
    //常量
    private final String preImgUrl = "/evo-apigw/evo-oss/";
    private final String aftImgUrl = "?token=";

    @Autowired
    private GeneralDaHuaIccHandler generalDaHuaIccHandler;

    @Resource
    private IOrgInfoService iOrgInfoService;

    public List<PedestrianRecordDaHuaDTO> pullRecord(Integer intervalDays, PedestrianIntegrationConfigDTO configDTO) {
        List<PedestrianRecordDaHuaDTO> recordDaHuaDTOList = new ArrayList<>();
        Integer pageNum = 1;
        List<PedestrianRecordDaHuaDTO> recordList = null;
        do {
            recordList = this.requestRecord(intervalDays, pageNum, configDTO);
            if (CollectionUtils.isEmpty(recordList)) {
                break;
            }
            this.handleImg(recordList, configDTO);
            recordDaHuaDTOList.addAll(recordList);
            ++pageNum;
        } while (!CollectionUtils.isEmpty(recordList) && recordList.size() == 500);
        return recordDaHuaDTOList;
    }

    public List<PedestrianRecordDaHuaDTO> pullFaceRecord(Integer intervalDays, PedestrianIntegrationConfigDTO configDTO) {
        List<PedestrianRecordDaHuaDTO> recordDaHuaDTOList = new ArrayList<>();
        Integer pageNum = 1;
        List<PedestrianRecordDaHuaDTO> recordList = null;
        do {
            recordList = this.requestFaceRecord(intervalDays, pageNum, configDTO);
            if (CollectionUtils.isEmpty(recordList)) {
                break;
            }
            this.handleFace(recordList, configDTO);
            recordDaHuaDTOList.addAll(this.handleCard(recordList, configDTO));
            log.info("recordDaHuaDTOList" + recordDaHuaDTOList);
            ++pageNum;
        } while (!CollectionUtils.isEmpty(recordList) && recordList.size() == 500);
        return recordDaHuaDTOList;
    }

    /**
     * 处理大华人行图片，将图片从大华平台下到华为OBS中（由于大华的这个图片需要token，而token是有时效的）
     */
    private void handleImg(List<PedestrianRecordDaHuaDTO> pedestrianRecordDaHuaDTOS, PedestrianIntegrationConfigDTO configDTO) {
        SecurityDaHuaDTO securityDaHuaDTO = generalDaHuaIccHandler.getToken(configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(),
                configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());

        pedestrianRecordDaHuaDTOS.stream().map(pedestrianRecordDaHuaDTO -> {
            //如果图片地址不为空，就下载下来
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(pedestrianRecordDaHuaDTO.getRecordImage())) {
                pedestrianRecordDaHuaDTO.setRecordImage(
                        UploadUtils.uploadImg(validImg(pedestrianRecordDaHuaDTO.getRecordImage(), configDTO, securityDaHuaDTO.getToken()))
                );
            }
            return pedestrianRecordDaHuaDTO;
        }).collect(Collectors.toList());
    }

    /**
     * 处理大华人行图片，将图片从大华平台下到华为OBS中（由于大华的这个图片需要token，而token是有时效的）
     */
    private void handleFace(List<PedestrianRecordDaHuaDTO> pedestrianRecordDaHuaDTOS, PedestrianIntegrationConfigDTO configDTO) {
        SecurityDaHuaDTO securityDaHuaDTO = generalDaHuaIccHandler.getToken(configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(),
                configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());

        pedestrianRecordDaHuaDTOS.stream().map(pedestrianRecordDaHuaDTO -> {
            //如果图片地址不为空，就下载下来
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(pedestrianRecordDaHuaDTO.getFacepath())) {
                pedestrianRecordDaHuaDTO.setFacepath(
                        UploadUtils.uploadImg(validImg(pedestrianRecordDaHuaDTO.getFacepath(), configDTO, securityDaHuaDTO.getToken()))
                );
            }
            return pedestrianRecordDaHuaDTO;
        }).collect(Collectors.toList());
    }

    /**
     * 大华人脸识别数据只有证件号 要根据证件号去查open-id
     *
     * @return
     */
    private List<PedestrianRecordDaHuaDTO> handleCard(List<PedestrianRecordDaHuaDTO> pedestrianRecordDaHuaDTOS, PedestrianIntegrationConfigDTO configDTO) {
        List<PedestrianRecordDaHuaDTO> newPedestrianRecordDaHuaDTOS = new ArrayList<>();
        pedestrianRecordDaHuaDTOS.stream().map(pedestrianRecordDaHuaDTO -> {
            //如果地址不为空，就下载下来
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(pedestrianRecordDaHuaDTO.getCardId())) {
                String personId = authAccountCentService.queryOpenIdbyCard(configDTO.getProjectId(), pedestrianRecordDaHuaDTO.getCardId());
                if (!StringUtils.isEmpty(personId)) {
                    pedestrianRecordDaHuaDTO.setPersonId(
                            Long.valueOf(personId)
                    );
                    newPedestrianRecordDaHuaDTOS.add(pedestrianRecordDaHuaDTO);
                }
                ;
            }
            return pedestrianRecordDaHuaDTO;
        }).collect(Collectors.toList());
        return newPedestrianRecordDaHuaDTOS;
    }

    /**
     * 将大华的图片组装为有效的图片地址（OSS方式）
     */
    private String validImg(String imgUrl, PedestrianIntegrationConfigDTO configDTO, String token) {
        return configDTO.getIpAndPort() + preImgUrl + imgUrl + aftImgUrl + token;
    }


    private List<PedestrianRecordDaHuaDTO> requestRecord(Integer intervalDays, Integer pageNum, PedestrianIntegrationConfigDTO configDTO) {
        HashMap<String, Object> params = new HashMap<>(2);
        params.put("pageNum", pageNum);
        params.put("pageSize", 500);
        int time = -(configDTO.getPullSecond());
        int afterTime = 3;
        if (intervalDays != null && intervalDays > 0) {
            time = -24 * 60 * intervalDays;
        }
        log.info("开始获取大华人行数据");
        // 时间范围：1~10；11~20；21~30；31~40；41~50；51~00
        log.error("集成配置类为{}", configDTO);
        params.put("startSwingTime", getIntervalSeconds(null, time));
        params.put("endSwingTime", getIntervalSeconds(null, afterTime));
        JSONObject resultObject = generalDaHuaIccHandler.post(DaHuaIccConstant.PEDESTRIAN_RECORD_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        log.info("获取大华人行数据结果:" + resultObject);
        log.info("获取大华人行数据结果:" + resultObject.getString("data"));
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.PEDESTRIAN_RECORD_URL, JSON.toJSONString(params), JSON.toJSONString(resultObject));
            return null;
        }
        String data = resultObject.getString("data");
        JSONObject dataObject = JSON.parseObject(data);
        String pageDataStr = dataObject.getString("pageData");
        if (StringUtils.isEmpty(pageDataStr)) {
            log.error("post path:{};params:{};pageData is null!", DaHuaIccConstant.PEDESTRIAN_RECORD_URL, JSON.toJSONString(params));
            return null;
        }
        List<PedestrianRecordDaHuaDTO> recordList = JSONObject.parseArray(pageDataStr, PedestrianRecordDaHuaDTO.class);
        return recordList;
    }

    private List<PedestrianRecordDaHuaDTO> requestFaceRecord(Integer intervalDays, Integer pageNum, PedestrianIntegrationConfigDTO configDTO) {
        HashMap<String, Object> params = new HashMap<>(2);
        params.put("pageNum", pageNum);
        params.put("pageSize", 500);
        params.put("searchType", 2);
        int time = -(configDTO.getPullSecond());
        int afterTime = 3;
        if (intervalDays != null && intervalDays > 0) {
            time = -24 * 60 * intervalDays;
        }
        log.info("开始获取大华人脸抓拍数据");
        // 时间范围：1~10；11~20；21~30；31~40；41~50；51~00
        log.error("集成配置类为{}", configDTO);
        params.put("startTime", getIntervalSeconds(null, time));
        params.put("endTime", getIntervalSeconds(null, afterTime));
        JSONObject resultObject = generalDaHuaIccHandler.get(DaHuaIccConstant.FACE_RECORD_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        log.info("获取大华人脸抓拍数据:" + resultObject);
        log.info("获取大华人脸数据结果:" + resultObject.getString("data"));
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.FACE_RECORD_URL, JSON.toJSONString(params), JSON.toJSONString(resultObject));
            return null;
        }
        String data = resultObject.getString("data");
        JSONObject dataObject = JSON.parseObject(data);
        String pageDataStr = dataObject.getString("pageData");
        if (StringUtils.isEmpty(pageDataStr)) {
            log.error("post path:{};params:{};pageData is null!", DaHuaIccConstant.PEDESTRIAN_RECORD_URL, JSON.toJSONString(params));
            return null;
        }
        List<PedestrianRecordDaHuaDTO> recordList = JSONObject.parseArray(pageDataStr, PedestrianRecordDaHuaDTO.class);
        log.info("success" + recordList);
        return recordList;
    }

    /**
     * 授权新增
     */
    public ResultJson addAuth(PedestrianIntegrationConfigDTO configDTO, PedestrianAuthDTO authDTO) {
        log.info("-----------开始授权-----------" + authDTO);
        if ((CollectionUtils.isEmpty(authDTO.getUserOpenIds()) && StringUtils.isEmpty(authDTO.getUserOpenId())) || CollectionUtils.isEmpty(authDTO.getThirdDeviceIdList())) {
            log.info("人信息或者设备信息为空");
            return ResultJson.fail("卡信息或者设备信息为空");
        }

        List<Map<String, Object>> resourceInfosMapList = new ArrayList<>();
        authDTO.getThirdDeviceIdList().forEach(thirdDeviceId -> {
            Map<String, Object> resourceInfosMap = new HashMap<>(2);
            resourceInfosMap.put("resouceCode", thirdDeviceId);
            resourceInfosMap.put("privilegeType", 1);
            resourceInfosMapList.add(resourceInfosMap);
        });

        Map<String, Object> params = new HashMap<>(3);
        params.put("cardNumbers", authDTO.getCardNumberList());
        params.put("cardPrivilegeDetails", resourceInfosMapList);
        params.put("timeQuantumId", 1);
        String api = DaHuaIccConstant.ADD_AUTH_URL;
        JSONObject resultObject = generalDaHuaIccHandler.post(api, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", api, JSON.toJSONString(params), JSON.toJSONString(resultObject));
            return ResultJson.fail("操作失败");
        }
        return ResultJson.success("操作成功");
    }

    /**
     * 授权删除
     */
    public ResultJson deleteAuth(PedestrianIntegrationConfigDTO configDTO, List<String> deletedCardNumberList) {
        Map<String, Object> params = new HashMap<>(2);
        params.put("cardNums", deletedCardNumberList);
        params.put("privilegeType", "3");
        String api = DaHuaIccConstant.DELETE_AUTH_URL;
        JSONObject resultObject = generalDaHuaIccHandler.post(api, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", api, JSON.toJSONString(params), JSON.toJSONString(resultObject));
            return ResultJson.fail("操作失败");
        }
        return ResultJson.success("操作成功");
    }

    /**
     * 处理部门字段 大华icc找不到对应组织时用集成配置中默认的部门
     */
    public String getUserDepartmentIds(PedestrianAuthDTO authDTO, PedestrianIntegrationConfigDTO configDTO) {
        List<Integer> orgIds = authDTO.getOrgIds();
        if (!CollectionUtils.isEmpty(orgIds)) {
            List<OrgInfo> orgInfos = iOrgInfoService.getList(configDTO.getProductId(), orgIds);
            return CollectionUtils.isEmpty(orgInfos) ? "1" : orgInfos.get(0).getOrgIndexCode();
        }
        return "1";
    }

    /**
     * 新增卡
     */
    public ResultJson addCardAuth(PedestrianIntegrationConfigDTO configDTO, PedestrianAuthDTO authDTO) {
        if (CollectionUtils.isEmpty(authDTO.getUserOpenIds()) && StringUtils.isEmpty(authDTO.getUserOpenId())) {
            return ResultJson.fail("无人员信息");
        }

        Map<String, Object> param = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Map<String, Object>> cardList = new ArrayList<>();

        authDTO.getCardNumberList().forEach(cardNum -> {
            Map<String, Object> cardInfo = new HashMap<>();
            cardInfo.put("cardNumber", cardNum);
            cardInfo.put("category", 0);
            cardInfo.put("cardType", 0);
            cardInfo.put("startDate", sdf.format(Objects.isNull(authDTO.getValidStartTime()) ? new Date() : authDTO.getValidStartTime()));
            cardInfo.put("endDate", sdf.format(Objects.isNull(authDTO.getValidEndTime()) ? new Date() : authDTO.getValidEndTime()));
            cardInfo.put("personId", StringUtils.isEmpty(authDTO.getUserOpenId())?authDTO.getUserOpenIds().get(0):authDTO.getUserOpenId());
            cardInfo.put("departmentId", getUserDepartmentIds(authDTO, configDTO));
            cardList.add(cardInfo);
        });
        param.put("cardList", cardList);
        String api = DaHuaIccConstant.CREATE_IDENTITY_URL;
        JSONObject resultObject = generalDaHuaIccHandler.post(api, param, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", api, JSON.toJSONString(param), JSON.toJSONString(resultObject));
            return ResultJson.fail("操作失败");
        }
        JSONObject data = JSON.parseObject(resultObject.getString("data"));
        log.error("add card data:{}", data);
        if (data != null) {
            JSONObject errorInfo = JSON.parseObject(data.getString("errorInfo"));
            log.error("add card errorInfo:{}", errorInfo);
            if (Objects.nonNull(errorInfo)){
                authDTO.getCardNumberList().forEach(cardNum -> {
                    String code = errorInfo.getString(cardNum);
                    log.error("add card code:{},cardNum:{}", code, cardNum);
                    if (StringUtils.isNotEmpty(code) && StringUtils.equals(code, DaHuaIccConstant.CARD_EXIST)) {
                        log.error("新增卡片 已存在 errorInfo:{},cardNum:{}", errorInfo, cardNum);
                        Map<String, Object> cardInfo = new HashMap<>();
                        cardInfo.put("cardNumber", cardNum);
                        cardInfo.put("category", 0);
                        cardInfo.put("startDate", sdf.format(Objects.isNull(authDTO.getValidStartTime()) ? new Date() : authDTO.getValidStartTime()));
                        cardInfo.put("endDate", sdf.format(Objects.isNull(authDTO.getValidEndTime()) ? new Date() : authDTO.getValidEndTime()));
                        cardInfo.put("personId", StringUtils.isEmpty(authDTO.getUserOpenId())?authDTO.getUserOpenIds().get(0):authDTO.getUserOpenId());
                        cardInfo.put("departmentId", getUserDepartmentIds(authDTO, configDTO));
                        String activeApi = DaHuaIccConstant.ACTIVE_CARD_URL;
                        generalDaHuaIccHandler.put(activeApi, cardInfo, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
                    }
                });
            }
        }
        return ResultJson.success("操作成功");

    }

    /**
     * 更新卡片信息
     */
    public ResultJson updateCardInfo(PedestrianIntegrationConfigDTO configDTO, PedestrianAuthDTO authDTO) {
        if (Objects.isNull(authDTO.getValidStartTime())) {
            return ResultJson.fail("没有起始时间");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String api = DaHuaIccConstant.UPDATE_IDENTITY_URL;
        authDTO.getCardNumberList().forEach(cardNum -> {
            Map<String, Object> cardInfo = new HashMap<>();
            cardInfo.put("cardNumber", cardNum);
            cardInfo.put("departmentId", getUserDepartmentIds(authDTO, configDTO));
            cardInfo.put("startDate", sdf.format(Objects.isNull(authDTO.getValidStartTime()) ? new Date() : authDTO.getValidStartTime()));
            cardInfo.put("endDate", sdf.format(Objects.isNull(authDTO.getValidEndTime()) ? new Date() : authDTO.getValidEndTime()));
            JSONObject resultObject = generalDaHuaIccHandler.put(api, cardInfo, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
            if (resultObject == null || !resultObject.getBoolean("success")) {
                log.error("post path:{};params:{};errMsg:{}", api, JSON.toJSONString(cardInfo), JSON.toJSONString(resultObject));
            }
        });
        return ResultJson.success("操作成功");
    }

    /**
     * 删除卡 第一步退卡 第二步删除卡
     */
    public ResultJson deleteCardAuth(PedestrianIntegrationConfigDTO configDTO, List<String> cardNumList) {
        Map<String, Object> card = new HashMap<>();
        Map<String, Object> detailParam = new HashMap<>();
        List<Integer> ids = new ArrayList<>();
        String api = DaHuaIccConstant.IDENTITY_URL_DETAIL;
        String finalApi = api;
        cardNumList.forEach(cardNum -> {
            detailParam.put("id", cardNum);
            JSONObject resultObject = generalDaHuaIccHandler.get(finalApi, detailParam, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
            if (resultObject == null || !resultObject.getBoolean("success")) {
                log.error("post path:{};params:{};errMsg:{}", finalApi, JSON.toJSONString(detailParam), JSON.toJSONString(resultObject));
            } else {
                JSONObject dataObject = resultObject.getJSONObject("data");
                ids.add(Integer.parseInt(dataObject.getString("id")));
            }
        });
        if (!CollectionUtils.isEmpty(ids)) {
            Map<String, Object> returnParam = new HashMap<>();
            returnParam.put("cardIds", ids);
            api = DaHuaIccConstant.RETURN_IDENTITY_URL;
            JSONObject resultObject = generalDaHuaIccHandler.put(api, returnParam, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
            if (resultObject != null && resultObject.getBoolean("success")) {
                Map<String, Object> param = new HashMap<>();
                param.put("cardIds", ids);

                api = DaHuaIccConstant.DELETE_IDENTITY_URL;
                resultObject = generalDaHuaIccHandler.delete(api, param, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
                if (resultObject == null || !resultObject.getBoolean("success")) {
                    log.error("post path:{};params:{};errMsg:{}", api, JSON.toJSONString(param), JSON.toJSONString(resultObject));
                    return ResultJson.fail("操作失败");
                }
                return ResultJson.success("操作成功");
            } else {
                return ResultJson.success("操作失败");
            }
        }
        return ResultJson.success("操作失败");
    }

    public ResultJson openDoor(PedestrianIntegrationConfigDTO configDTO, DeviceDTO deviceDTO, DoorActionEnum doorAction) {
        String api;
        switch (doorAction) {
            case REMOTELY_OPEN:
                api = DaHuaIccConstant.OPEN_DOOR;
                break;
            default:
                return ResultJson.fail("无对应设备操作");
        }
        HashMap<String, Object> params = new HashMap<>(1);
        params.put("channelCodeList", Arrays.asList(deviceDTO.getThirdDeviceId()));
        JSONObject resultObject = generalDaHuaIccHandler.post(api, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", api, JSON.toJSONString(params), JSON.toJSONString(resultObject));
            return ResultJson.fail("操作失败");
        }
        return ResultJson.success();
    }

    public String getIntervalMinutes(Date date, int interval) {
        Calendar calendar = Calendar.getInstance();
        if (date == null) {
            calendar.setTime(new Date());
        } else {
            calendar.setTime(date);
        }
        calendar.set(Calendar.MINUTE, (calendar.get(Calendar.MINUTE)) / 10 * 10);
        calendar.set(Calendar.SECOND, 0);
        calendar.add(Calendar.MINUTE, interval);
        Date resultDate = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(resultDate);
    }

    public String getIntervalSeconds(Date date, int interval) {
        Calendar calendar = Calendar.getInstance();
        if (date == null) {
            calendar.setTime(new Date());
        } else {
            calendar.setTime(date);
        }
        calendar.set(Calendar.SECOND, (calendar.get(Calendar.SECOND)) / 10 * 10);
        calendar.add(Calendar.SECOND, interval);
        Date resultDate = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(resultDate);
    }

    public Long createIdentity(PedestrianIntegrationConfigDTO configDTO) {
        IdentityDaHuaDTO identityDaHuaDTO = IdentityDaHuaDTO.builder().name("普通员工").description("默认身份").build();
        Map<String, Object> params = JSONObject.parseObject(JSONObject.toJSONString(identityDaHuaDTO), Map.class);
        JSONObject resultObject = generalDaHuaIccHandler.post(DaHuaIccConstant.CREATE_IDENTITY_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.CREATE_IDENTITY_URL, JSON.toJSONString(params), JSON.toJSONString(resultObject));
            throw new BusinessException(JSON.toJSONString(resultObject));
        }
        return resultObject.getLong("data");
    }

    public AuthAccountMapping createUser(PedestrianIntegrationConfigDTO configDTO, UserDaHuaIccDTO userDaHuaIccDTO) {
        Map<String, Object> params = JSONObject.parseObject(JSONObject.toJSONString(userDaHuaIccDTO), Map.class);
        JSONObject resultObject = generalDaHuaIccHandler.post(DaHuaIccConstant.CREATE_USER_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.CREATE_USER_URL, JSON.toJSONString(params), JSON.toJSONString(resultObject));
            throw new BusinessException(JSON.toJSONString(resultObject));
        }
        AuthAccountMapping authAccountMapping = new AuthAccountMapping();
        String data = resultObject.getString("data");
        JSONObject dataObject = JSON.parseObject(data);
        String idString = dataObject.getString("id");
        authAccountMapping.setOpenId(idString);
        authAccountMapping.setOpenCode(userDaHuaIccDTO.getCode());
        return authAccountMapping;
    }

    public List queryIdentity(PedestrianIntegrationConfigDTO configDTO) {
        JSONObject resultObject = generalDaHuaIccHandler.get(DaHuaIccConstant.QUERY_IDENTITY_URL, null, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};errMsg:{}", DaHuaIccConstant.QUERY_IDENTITY_URL, JSON.toJSONString(resultObject));
            throw new BusinessException(JSON.toJSONString(resultObject));
        }

        return resultObject.getObject("data", List.class);
    }

    public AuthAccountMapping queryUser(PedestrianAuthDTO pedestrianAuthDTO, PedestrianIntegrationConfigDTO configDTO) {
        AuthAccountMapping authAccountMapping = null;
        HashMap<String, Object> params = new HashMap<>();
        params.put("id", pedestrianAuthDTO.getUserOpenId());

        JSONObject resultObject = generalDaHuaIccHandler.get(DaHuaIccConstant.QUERY_USER_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.QUERY_USER_URL, JSON.toJSONString(params), JSON.toJSONString(resultObject));
            //throw new BusinessException(JSON.toJSONString(resultObject));
            return authAccountMapping;
        }
        JSONObject data = resultObject.getJSONObject("data");
        if (!data.isEmpty()) {
            UserDaHuaIccDTO userDaHuaIccDTO = data.toJavaObject(UserDaHuaIccDTO.class);
            authAccountMapping = new AuthAccountMapping();
            authAccountMapping.setOpenId(userDaHuaIccDTO.getId());
            authAccountMapping.setOpenCode(userDaHuaIccDTO.getCode());
            //人脸是否变更 如果变更 同步到大华设备
            if ((!CollectionUtils.isEmpty(pedestrianAuthDTO.getThirdDeviceIdList())) && StringUtils.isNotEmpty(pedestrianAuthDTO.getFaceUrl())) {
                AtomicBoolean needUpdateFace = new AtomicBoolean(false);
                String imageUrl = getImageUrl(pedestrianAuthDTO, configDTO);
                if (!CollectionUtils.isEmpty(userDaHuaIccDTO.getPersonBiosignatures())) {
                    userDaHuaIccDTO.getPersonBiosignatures().forEach(personBiosignatures -> {
                        if (personBiosignatures.getType() == DaHuaIccConstant.DAHUA_FACE_TYPE && !StringUtils.equals(personBiosignatures.getPath(), imageUrl)) {
                            needUpdateFace.set(true);
                        }
                    });
                } else {
                    needUpdateFace.set(true);
                }

                if (needUpdateFace.get()) {
                    UserDaHuaIccPersonBiosignatures userDaHuaIccPersonBiosignatures = new UserDaHuaIccPersonBiosignatures();
                    userDaHuaIccPersonBiosignatures.setType(DaHuaIccConstant.DAHUA_FACE_TYPE);
                    userDaHuaIccPersonBiosignatures.setIndex(1);
                    userDaHuaIccPersonBiosignatures.setPath(imageUrl);
                    String paperNumber = userDaHuaIccDTO.getPhone();
                    Integer paperType = -1;
                    if (!org.springframework.util.StringUtils.isEmpty(paperNumber) && IdcardUtil.isValidCard(paperNumber)) {
                        paperType = DaHuaIccConstant.DEFAULT_PAPER_TYPE;
                        paperNumber = userDaHuaIccDTO.getPaperNumber();
                    }
                    UserDaHuaIccDTO userDaHuaUpdate = UserDaHuaIccDTO.builder().id(userDaHuaIccDTO.getId())
                            .code(GeneralDaHuaHandler.generateOpenCode(Integer.parseInt(userDaHuaIccDTO.getId()), configDTO.getProjectId()))
                            .departmentId(userDaHuaIccDTO.getDepartmentId())
                            .name(userDaHuaIccDTO.getName())
                            .paperNumber(paperNumber)
                            .paperType(paperType)
                            .paperAddress(DaHuaIccConstant.DEFAULT_ADDRESS)
                            .phone(userDaHuaIccDTO.getPhone())
                            .service(DaHuaIccConstant.DEFAULT_SERVICE)
                            .personBiosignatures(Collections.singletonList(userDaHuaIccPersonBiosignatures))
                            .sex(userDaHuaIccDTO.getSex() == null ? 0 : userDaHuaIccDTO.getSex()).build();
                    updateUser(configDTO, userDaHuaUpdate);
                }
            }
        }
        return authAccountMapping;
    }

    public void updateUser(PedestrianIntegrationConfigDTO configDTO, UserDaHuaIccDTO userDaHuaIccDTO) {
        Map<String, Object> params = JSONObject.parseObject(JSONObject.toJSONString(userDaHuaIccDTO), Map.class);
        JSONObject resultObject = generalDaHuaIccHandler.put(DaHuaIccConstant.UPDATE_USER_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.UPDATE_USER_URL, JSON.toJSONString(params), JSON.toJSONString(resultObject));
            throw new BusinessException(JSON.toJSONString(resultObject));
        }
    }

    public void deleteUser(PedestrianIntegrationConfigDTO configDTO, PedestrianAuthDTO pedestrianAuthDTO) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("ids", Collections.singletonList(Integer.parseInt(pedestrianAuthDTO.getUserOpenId())));
        JSONObject resultObject = generalDaHuaIccHandler.post(DaHuaIccConstant.DELETE_USER_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.DELETE_USER_URL, JSON.toJSONString(params), JSON.toJSONString(resultObject));
            throw new BusinessException(JSON.toJSONString(resultObject));
        }
    }

    public String getUserId(PedestrianIntegrationConfigDTO configDTO) {
        HashMap<String, Object> params = new HashMap<>(1);
        JSONObject resultObject = generalDaHuaIccHandler.get(DaHuaIccConstant.GENERATE_USER_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.GENERATE_USER_URL, JSON.toJSONString(params), JSON.toJSONString(resultObject));
            throw new BusinessException(JSON.toJSONString(resultObject));
        }
        return resultObject.getJSONObject("data").getString("id");
    }

    public String getImageUrl(PedestrianAuthDTO pedestrianAuthDTO, PedestrianIntegrationConfigDTO configDTO) {
        if (StringUtils.isEmpty(pedestrianAuthDTO.getFaceUrl())) {
            return null;
        }
        HashMap<String, Object> params = new HashMap<>(1);
        params.put("imageUrl", pedestrianAuthDTO.getFaceUrl());
        JSONObject resultObject = generalDaHuaIccHandler.upload(DaHuaIccConstant.UPLOAD_IMAGE_URL, params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (resultObject == null || !resultObject.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.GENERATE_USER_URL, JSON.toJSONString(params), JSON.toJSONString(resultObject));
            return null;
            //throw new BusinessException(JSON.toJSONString(resultObject));
        }
        return resultObject.getJSONObject("data").getString("fileUrl");
    }

    public ResultJson getInsideQrCode(PedestrianIntegrationConfigDTO configDTO, OpenDoorRecordDTO openDoorRecordDTO) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("id", openDoorRecordDTO.getCode());

        JSONObject object = generalDaHuaIccHandler.get(DaHuaIccConstant.QUERY_USER_URL, param, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
        if (object == null || !object.getBoolean("success")) {
            log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.QUERY_USER_URL, JSON.toJSONString(param), JSON.toJSONString(object));
            return ResultJson.fail("人员未同步");
        }
        JSONObject data = object.getJSONObject("data");
        if (!data.isEmpty()) {
            UserDaHuaIccDTO userDaHuaIccDTO = data.toJavaObject(UserDaHuaIccDTO.class);
            HashMap<String, Object> params = new HashMap<>();
            params.put("personCode", userDaHuaIccDTO.getCode());
            JSONObject resultObject = generalDaHuaIccHandler.get(DaHuaIccConstant.INSIDE_QR_CODE_URL + '/' + userDaHuaIccDTO.getCode(), params, configDTO.getProjectId(), configDTO.getProductId(), configDTO.getIpAndPort(), configDTO.getLoginName(), configDTO.getPassword(), configDTO.getAk(), configDTO.getSk());
            if (resultObject == null || !resultObject.getBoolean("success")) {
                log.error("post path:{};params:{};errMsg:{}", DaHuaIccConstant.INSIDE_QR_CODE_URL, JSON.toJSONString(params), JSON.toJSONString(resultObject));
                return ResultJson.fail("获取二维码失败");
            } else {
                return ResultJson.success(CodeEnum.SUCCESS.description, resultObject.getString("data"));
            }
        }
        return ResultJson.fail("人员未同步");
    }
}
